//
//  QRCodeMyCardViewController.swift
//  CXCWeibo
//
//  Created by cxc on 15/6/30.
//  Copyright © 2015年 china. All rights reserved.
//

import UIKit
import FFAutoLayout

class QRCodeMyCardViewController: UIViewController {
    
    lazy var iconView:UIImageView = UIImageView()
    
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        view.addSubview(iconView)
        iconView.ff_AlignInner(ff_AlignType.CenterCenter, referView: view, size: CGSize(width: 200, height: 200))
        iconView.backgroundColor = UIColor.lightGrayColor()
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()

        iconView.image = generateQRCodeImage()
        
    }
    private func generateQRCodeImage() ->UIImage {
        // 建立二维码滤镜
        let qrfilter = CIFilter(name: "CIQRCodeGenerator")!
        qrfilter.setDefaults()
        
        //通过KVC设置滤镜信息
        qrfilter.setValue("18637549740".dataUsingEncoding(NSUTF8StringEncoding), forKey: "inputMessage")
        
        //获取结果
        let ciImage = qrfilter.outputImage
        print(ciImage.extent)
        
        //放大图片
        let transform = CGAffineTransformMakeScale(15, 15)
        let transformImage = ciImage.imageByApplyingTransform(transform)
        
        //添加颜色滤镜
        let colorFilter = CIFilter(name: "CIFalseColor")!
        colorFilter.setDefaults()
        colorFilter.setValue(transformImage, forKey: "inputImage")
        //前景色和背景色
        colorFilter.setValue(CIColor(color: UIColor.blackColor()), forKey: "inputColor0")
        colorFilter.setValue(CIColor(color: UIColor.whiteColor()), forKey: "inputColor1")
        
        let resultImage = colorFilter.outputImage
        let avatar = UIImage(named: "me")
        return insertAvatarImage(UIImage(CIImage:resultImage), avatar: avatar!)
        
    }
    private func insertAvatarImage(image:UIImage,avatar:UIImage)->UIImage{
        UIGraphicsBeginImageContext(image.size)
        
        let rect = CGRect(origin: CGPointZero, size: image.size)
        image.drawInRect(rect)
        
        //添加图像
        let w = rect.width * 0.25
        let x = (rect.width - w) * 0.5
        let y = (rect.height - w) * 0.5
        avatar.drawInRect(CGRect(x: x, y: y, width: w, height: w))
        
        let result = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return result
    }


}
